package com.windchime.blog.controller.admin;

import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.User;
import com.windchime.blog.entity.vo.UserSearch;
import com.windchime.blog.result.R;
import com.windchime.blog.service.UserService;
import com.windchime.blog.utils.StringSplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author WindChime
 * @since 2021-07-31
 */
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {

    @Autowired
    private UserService userService;

    /**
     * 带条件分页查询
     * @param page 当前页
     * @param limit 当前页数量
     * @param userSearch 查询条件的vo
     * @return users
     */
    @GetMapping("/selectUserList")
    public R selectUserList(int page, int limit, UserSearch userSearch) {

        PageInfo<User> users = userService.selectUserList(page, limit, userSearch);
        return R.ok().code(0).msg("").count(users.getTotal()).data("users", users.getList());
    }

    /**
     * 添加用户
     * @param user 用户
     * @return true
     */
    @PostMapping("/saveUser")
    public R saveUser(User user) {
        boolean b = userService.saveUser(user);
        if (b) {
            return R.ok().msg("添加成功");
        } else {
            return R.error().msg("已有该用户名,请重新输入用户名");
        }
    }

    /**
     * 修改用户
     * @param user 用户
     * @return true
     */
    @PostMapping("/editUser")
    public R editUser(User user) {
        boolean b = userService.editUser(user);
        if (b) {
            return R.ok().msg("修改成功");
        } else {
            return R.error().msg("用户名已被使用,请重新修改");
        }
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return true
     */
    @GetMapping("/deleteUser/{id}")
    public R deleteUser(@PathVariable Long id) {
        boolean b = userService.removeById(id);
        if (b) {
            return R.ok().msg("删除成功");
        } else {
            return R.error().msg("删除失败");
        }
    }

    /**
     * 批量删除
     * @param ids ids数组字符串
     * @return true
     */
    @GetMapping("/deleteUsers/{ids}")
    public R deleteUsers(@PathVariable String ids) {
        List<Long> idList = StringSplitUtil.split(ids, ",");
        boolean b = userService.removeByIds(idList);
        if (b) {
            return R.ok().msg("批量删除成功");
        } else {
            return R.error().msg("批量删除失败");
        }
    }

}

